﻿namespace LxBasic
{
    public struct FaceGeomCalc
    {
        private double areaSum;//如果这几个三角面不在一个平面，不至于出错
        private Vector3d centerP3;
        private Vector3d normalP2;
        public void AddTriangle(in Vector3d p0, in Vector3d p1, in Vector3d p2)
        {
            Vector3d norP2 = Vector3d.CrossProduct(p1 - p0, p2 - p1);
            double area = norP2.Length();
            areaSum += area;
            centerP3 += area * (p0 + p1 + p2);
            normalP2 += norP2;
        }
        public (Vector3d Normal, Vector3d Center) GetResult()
            => (0.5 * normalP2, LxTool.OneThird / areaSum * centerP3);
#if DEBUG
        public static void Test()
        {
            test1();
            test2();
        }
        public static void test1()
        {
            Vector3d[] vs = new Vector3d[3];
            vs[0] = new Vector3d(0, 0, 0);
            vs[1] = new Vector3d(1, 0, 0);
            vs[2] = new Vector3d(0, 1, 0);
            FaceGeomCalc f = new FaceGeomCalc();
            f.AddTriangle(vs[0], vs[1], vs[2]);
            Console.WriteLine("Points:");
            foreach (var v in vs)
            {
                Console.WriteLine(v);
            }
            var r = f.GetResult();
            Console.WriteLine($"Normal:{r.Normal};Center:{r.Center}");
        }
        public static void test2()
        {
            Vector3d[] vs = new Vector3d[4];
            vs[0] = new Vector3d(0, 0, 0);
            vs[1] = new Vector3d(1, 0, 0);
            vs[2] = new Vector3d(1, 1, 0);
            vs[3] = new Vector3d(0, 1, 0);
            FaceGeomCalc f = new FaceGeomCalc();
            f.AddTriangle(vs[0], vs[1], vs[2]);
            f.AddTriangle(vs[0], vs[2], vs[3]);
            Console.WriteLine("Points:");
            foreach (var v in vs)
            {
                Console.WriteLine(v);
            }
            var r = f.GetResult();
            Console.WriteLine($"Normal:{r.Normal};Center:{r.Center}");
        }
#endif
    }
}


